package com.zichen.pr.system.controller;

import com.zichen.pr.common.constant.UserConstants;
import com.zichen.pr.common.core.controller.BaseController;
import com.zichen.pr.common.core.domain.entity.SysDept;
import com.zichen.pr.common.core.domain.result.Result;
import com.zichen.pr.system.service.SysDeptService;
import com.zichen.pr.util.DateUtils;
import com.zichen.pr.util.SecurityUtils;
import com.zichen.pr.util.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * @program: zichen
 * @description: 部门
 * @author: rzhang
 * @create: 2021-04-22 15:02
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {

    @Resource(name = "sysDeptService")
    private SysDeptService sysDeptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public Result list(SysDept dept) {
        List<SysDept> depts = sysDeptService.selectDeptList(dept);
        return Result.success(depts);
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public Result excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = sysDeptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        return Result.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public Result getInfo(@PathVariable Long deptId) {
        return Result.success(sysDeptService.getById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public Result treeselect(SysDept dept) {
        List<SysDept> depts = sysDeptService.selectDeptList(dept);
        return Result.success(sysDeptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public Result roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = sysDeptService.selectDeptList(new SysDept());
        Result ajax = Result.success();
        ajax.put("checkedKeys", sysDeptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", sysDeptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @PostMapping
    public Result add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return Result.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setCreateTime(DateUtils.getNowDate());
        return toAjax(sysDeptService.save(dept));
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @PutMapping
    public Result edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(sysDeptService.checkDeptNameUnique(dept))) {
            return Result.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return Result.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus())
                && sysDeptService.selectNormalChildrenDeptById(dept.getDeptId()) > 0) {
            return Result.error("该部门包含未停用的子部门！");
        }
        dept.setUpdateBy(SecurityUtils.getUsername());
        dept.setUpdateTime(DateUtils.getNowDate());
        return toAjax(sysDeptService.updateById(dept));
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @DeleteMapping("/{deptId}")
    public Result remove(@PathVariable Long deptId) {
        if (sysDeptService.hasChildByDeptId(deptId)) {
            return Result.error("存在下级部门,不允许删除");
        }
        if (sysDeptService.checkDeptExistUser(deptId)) {
            return Result.error("部门存在用户,不允许删除");
        }
        return toAjax(sysDeptService.deleteDeptById(deptId));
    }
}
